<template>
  <a-form-model ref="userForm" layout="vertical" :model="form" :rules="rules">
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.employeeCode" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.a0102Name" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.a0103Name" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-form-model-item label="" style="margin: 0;display: none">
      <a-input v-model="form.a0104Name" placeholder="" style="display: none" />
    </a-form-model-item>
    <a-row :gutter="8"  v-if="!editFlag">
      <a-col :span="24">
        <a-form-model-item label="选择人员">
          <a-cascader
                      :options="options"
                      :load-data="loadData"
                      placeholder="请选择"
                      change-on-select
                      @change="onChange"
          />
<!--          <a-input v-else v-model="form.fullName" placeholder="" disabled/>-->
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-model-item label="用户姓名">
          <a-input v-model="form.fullName" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-model-item label="所属机构">
          <a-input v-model="form.a0102Name" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="所属科室">
          <a-input v-model="form.a0103Name" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-model-item label="职务">
          <a-input v-model="form.a0104Name" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="联系方式">
          <a-input v-model="form.a0105" placeholder="" disabled/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-model-item label="管理区域（可多选）" prop="userOrgIds">
          <a-tree-select
              v-model="form.userOrgIds"
              style="width: 100%"
              :tree-data="orgTreeData"
              tree-checkable
              :show-checked-strategy="SHOW_PARENT"
              search-placeholder="请选择"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24" v-for="(item, index) in form.permissionGroup" :key="index">
      <a-col :span="8">
        <a-form-model-item style="margin-bottom: 0px;" :label="index===0 ? '角色':''" :key="'role_'+index" prop="a0202">
          <a-select v-model="form.permissionGroup[index].a0202" placeholder="请选择" @change="handleChangeA0202(index,$event)">
            <a-select-option v-for="(item) in a0202DictList" :key="item.dictKey" :value="item.dictKey" :disabled="item.status==='0'">
              {{item.dictValue}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="16">
        <a-form-model-item class="custom" style="margin-bottom: 0px;" :label="index===0 ? '权限配置（可多选）':''" :key="'permission_'+index">
          <a-tree-select
              ref="permission"
              v-model="form.permissionGroup[index].objectIds"
              :tree-data="busiRouterTreeData"
              tree-checkable
              :show-checked-strategy="SHOW_CHILD"
              search-placeholder="请选择"
              :disabled="form.permissionGroup[index].disabled!==undefined"
          />
          <a-icon
              v-if="form.permissionGroup.length > 1"
              class="dynamic-delete-button"
              type="minus-circle-o"
              :disabled="form.permissionGroup.length === 1"
              @click="removePermission(item)"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-button type="dashed" style="width: 100%" @click="addBusiRole">
          <a-icon type="plus" /> 新增角色
        </a-button>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="24">
        <a-form-model-item label="驾驶舱权限">
          <a-input v-model="form.fieldA" placeholder="请选择" />
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>
</template>
<script>
import {getPermissionParams,getOrgOrUserInZzdForLocal,getUserDetailInfoInZzd} from '@/services/system/whdngxlApi'
import {getBatchDict} from "@/services/system/api"
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const SHOW_CHILD = TreeSelect.SHOW_CHILD;
export default {
  props: {
    userInfo: {
      type: Object,
      default: () => {},
      required: false
    }
  },
  data() {
    return {
      rules: {
        userName: [{ required: true, message: '请选择人员', trigger: 'blur' }],
      },
      options: [],
      form: {
        //sys_user表数据
        userId: '',
        employeeCode: '',
        userName: '',
        fullName: '',
        userType: '10',
        status: '1',
        //a01表数据
        a0102: '',
        a0102Name: '',
        a0103: '',
        a0103Name: '',
        a0104: '',
        a0104Name: '',
        a0105: '',
        //a02表数据+a03表数据
        permissionGroup: [{
          a0202: null,//人员类型
          objectType: 'router',//权限类型
          objectIds: [],//权限id
        }],
        //数据权限
        userOrgIds: [],
      },
      //路由权限
      routerPermission: [
        {
          routerId: '1',
          key: '',
          title: ''
        }
      ],
      busiRouterTreeData: [],
      SHOW_PARENT,
      SHOW_CHILD,
      orgTreeData: [],
      a0202DictList: [],
      a0202DictListTemp: [],
      editFlag: false
    };
  },
  created() {
    this.$http.post(getPermissionParams, {}).then(res => {
      const data = res.result
      this.orgTreeData = data.orgTreeData
      this.a0202DictList = data.a0202DictList
      this.busiRouterTreeData = data.busiRouterTreeData
      if(this.userInfo){
        this.editFlag = true
        this.form = JSON.parse(JSON.stringify(this.userInfo))
      }
    })

    if(!this.userInfo){
      //实际是调取浙政钉的接口
      this.$http.post(getOrgOrUserInZzdForLocal, {searchOrg: true}).then(res => {
        this.options = res.result
        this.options.forEach(item =>{
          item.isLeaf = item.leaf
        })
      })
    }

  },
  methods:{
    onChange(value,selectedOptions) {
      const lastItem = value[value.length - 1]
      if(lastItem.indexOf('GE_') > -1){
        const targetOption = selectedOptions[selectedOptions.length - 1];
        this.form.fullName = targetOption.employeeName
        this.$http.post(getUserDetailInfoInZzd, {employeeCode: lastItem}).then(res => {
          Object.assign(this.form, res.result)
        })
      }
    },
    loadData(selectedOptions) {
      console.log(selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;

      this.$http.post(getOrgOrUserInZzdForLocal, {searchOrg: targetOption.searchOrg,
        searchUser: targetOption.searchUser,organizationCode: targetOption.organizationCode}).then(res => {
        const list = res.result
        list.forEach(item =>{
          item.isLeaf = item.leaf
        })
        targetOption.loading = false;
        targetOption.children = list;
        this.options = [...this.options];
      })
    },
    removePermission(item){
      let index = this.form.permissionGroup.indexOf(item);
      if (index !== -1) {
        this.form.permissionGroup.splice(index, 1);
      }
    },
    lookForAllByKey(data = [],key,disabled) {
      for (let item of data) {
        if(item.key === key) {
          item.disabled = disabled
        }
        if (item.children && item.children.length) this.lookForAllByKey(item.children,key,disabled)
      }
    },
    lookForAllByParentKey(data = [],parentKey,disabled) {
      for (let item of data) {
        if(item.parentKey === parentKey) {
          item.disabled = disabled
        }
        if (item.children && item.children.length) this.lookForAllByParentKey(item.children,parentKey,disabled)
      }
    },
    handleChangeA0202(index,value){
      if(['00','01'].indexOf(value) > -1){
        this.form.permissionGroup[index].disabled = true
        this.form.permissionGroup[index].objectIds = ['fdc300bf79bb429bb98fc3b820c38289','d13f472ea38444b495ac4d65dcc8cf55']//权限管理模块
      }else if(['02','03'].indexOf(value) > -1){
        this.form.permissionGroup[index].disabled = undefined
        this.form.permissionGroup[index].objectIds = []
        this.disabledPromissionRouter()
      }
    },
    //禁用权限管理模块
    disabledPromissionRouter(){
      const busiRouterTreeData = JSON.parse(JSON.stringify(this.busiRouterTreeData))
      this.lookForAllByKey(busiRouterTreeData,'fdc300bf79bb429bb98fc3b820c38289',true)
      this.lookForAllByKey(busiRouterTreeData,'d13f472ea38444b495ac4d65dcc8cf55',true)
      this.busiRouterTreeData = busiRouterTreeData
    },
    addBusiRole(){
      this.form.permissionGroup.push({
        a0202: null,
        objectType: 'router',
        objectIds: [],
      })
    },
    getAllNodesForTreeByKey(data = [],arr = [],key,parentKey = null) {
      for (let item of data) {
        if(parentKey === null){
          if(item.key === key) {
            arr.push(item.key)
            if (item.children && item.children.length) this.getAllNodesForTreeByKey(item.children,arr,null,item.key)
          }else {
            if (item.children && item.children.length) this.getAllNodesForTreeByKey(item.children,arr,key)
          }
        }else {
          if(item.parentKey === parentKey) {
            arr.push(item.key)
            if (item.children && item.children.length) this.getAllNodesForTreeByKey(item.children,arr,null,item.key)
          }
        }
      }
      return arr
    },
    saveOrUpdate() {
      return new Promise((resolve, reject) => {
        this.$refs.userForm.validate(valid => {
          if (valid) {
            let flag = true
            if(!this.form.employeeCode){
              alert('请选择人员')
              flag = false
            }
            if(this.form.userOrgIds.length === 0){
              alert('请配置管理区域')
              flag = false
            }
            const item = this.form.permissionGroup[0]
            if(!item.a0202){
              alert('请配置角色')
              flag = false
            }
            if(item.objectIds.length === 0){
              alert('请配置角色权限')
              flag = false
            }
            if(flag === false){
              reject(false)
              return
            }
            const formData = JSON.parse(JSON.stringify(this.form))
            formData.userName = formData.employeeCode
            resolve(formData)
          } else {
            reject(false)
          }
        });
      })

    },
  },
  computed: {

  },
};
</script>
<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 5px;
}
.custom {
  .ant-form-item-children {
    span {
      width: 95%;
    }
  }
}
</style>
